<template>
  <div class="base-info-box">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基础设置</span>
              <el-popover placement="bottom" :width="200" trigger="click">
                <template #reference>
                  <el-button type="primary" link>
                    <el-icon><Setting /></el-icon>
                  </el-button>
                </template>
                <div class="setting-popover">
                  <div class="setting-title">显示项设置</div>
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange" size="small">全选</el-checkbox>
                  <el-checkbox-group v-model="visibleFields" @change="handleCheckedChange">
                    <el-checkbox v-for="field in fieldSettings" :key="field.prop" :label="field.prop" size="small">
                      {{ field.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-popover>
            </div>
          </template>
          <el-form ref="formRef" :model="formData" label-position="top" :inline="true" class="base-form">
            <el-form-item v-show="visibleFields.includes('name')" label="站点名称" prop="name">
              <template v-if="editingField !== 'name'">
                <span class="editable-text" @click="startEdit('name')">
                  <span class="text-content">{{ formData.name || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.name" @blur="finishEdit('name')" v-focus placeholder="输入站点名称" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('domain')" label="静态域名" prop="domain">
              <template v-if="editingField !== 'domain'">
                <span class="editable-text" @click="startEdit('domain')">
                  <span class="text-content">{{ formData.domain || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.domain" @blur="finishEdit('domain')" v-focus placeholder="输入静态域名" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('uri')" label="URI" prop="uri">
              <template v-if="editingField !== 'uri'">
                <span class="editable-text" @click="startEdit('uri')">
                  <span class="text-content">{{ formData.uri || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.uri" @blur="finishEdit('uri')" v-focus placeholder="输入URI" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('title')" label="站点标题" prop="title">
              <template v-if="editingField !== 'title'">
                <span class="editable-text" @click="startEdit('title')">
                  <span class="text-content">{{ formData.title || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.title" @blur="finishEdit('title')" v-focus placeholder="输入站点标题" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('description')" label="站点描述" prop="description">
              <template v-if="editingField !== 'description'">
                <span class="editable-text" @click="startEdit('description')">
                  <span class="text-content">{{ formData.description || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.description" type="textarea" autosize @blur="finishEdit('description')" v-focus placeholder="输入站点描述" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('keywords')" label="关键字" prop="keywords">
              <template v-if="editingField !== 'keywords'">
                <span class="editable-text" @click="startEdit('keywords')">
                  <span class="text-content">{{ formData.keywords || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.keywords" type="textarea" autosize @blur="finishEdit('keywords')" v-focus placeholder="输入关键字" />
            </el-form-item>
            
            <el-form-item v-show="visibleFields.includes('logo')" label="站点图标" prop="logo">
              <div v-if="editingField !== 'logo'">
                <span class="editable-text" @click="startEdit('logo')">
                  <img v-if="formData.logo" class="text-content logo-img" :src="formData.logo" alt="" />
                  <span v-else class="text-content">未设置</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </div>
              <div v-else class="logo-setting">
                <img class="text-content logo-img" :src="formData.logo" alt="" />
              </div>
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('themeColor')" label="主题色" prop="themeColor">
              <el-color-picker v-model="formData.themeColor" @change="handleThemeColorChange" />
            </el-form-item>

            <el-form-item v-show="visibleFields.includes('setting.statisticId')" label="百度统计ID" prop="setting.statisticId">
              <template v-if="editingField !== 'setting.statisticId'">
                <span class="editable-text" @click="startEdit('setting.statisticId')">
                  <span class="text-content">{{ formData.setting?.statisticId || '-' }}</span>
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </span>
              </template>
              <el-input v-else v-model="formData.setting.statisticId" @blur="finishEdit('setting.statisticId')" v-focus placeholder="输入百度统计ID" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>预览</span>
          </template>
          <div class="baidu-box">
            <div class="head">
              <div class="title-box">
                <div class="ico-box">
                  <img src="@/assets/baidu.png" alt="">
                </div>
                <div class="site-title">百度一下</div>
              </div>
              <div class="rigth-icon">
                <i class="iconfont">&#xe65a;</i>
                <i class="iconfont">&#xe636;</i>
                <i class="iconfont">&#xeb6a;</i>
              </div>
            </div>
            <div class="preview-content">
              <div class="des1">百度为您找到相关结果:</div>
              <div class="site-info">
                <div class="site-title">
                  <div class="name">{{formData.title}}</div>
                  <div class="guanfang">官方</div>
                </div>
                <div class="site-body">
                  <div class="site-logo">
                    <img v-if="formData.logo" :src="formData.logo" alt="logo" />
                    <span v-else>无Logo</span>
                  </div>
                  <div class="site-info-right">
                    <div class="site-des">{{ formData.description || '暂无描述' }}</div>
                    <div class="site-domain">{{ formData.domain || '暂无网址' }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <FilesUpload v-model:showDialog="showImgUpload" allow=".ico" :limit="1" @getFileList="getImage"></FilesUpload>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Setting } from '@element-plus/icons-vue'
import { updateSite } from '@/api/site'
import { FilesUpload } from '@ruifox-cms/components'

const props = defineProps({
  form: {
    type: Object,
    required: true
  }
})
const emits = defineEmits(['update'])
const formData = ref({ ...props.form })
watch(
  () => props.form,
  newVal => {
    formData.value = { ...newVal }
  },
  { deep: true }
)

// 显示控制相关
const fieldSettings = [
  { prop: 'name', label: '站点名称' },
  { prop: 'domain', label: '静态域名' },
  { prop: 'uri', label: 'URI' },
  { prop: 'title', label: '站点标题' },
  { prop: 'description', label: '站点描述' },
  { prop: 'keywords', label: '关键字' },
  { prop: 'themeColor', label: '主题色' },
  { prop: 'setting.statisticId', label: '百度统计ID' },
  { prop: 'logo', label: '站点图标' }
]

const visibleFields = ref(fieldSettings.map(field => field.prop))
const checkAll = ref(true) // 是否全选
const isIndeterminate = ref(false) // 是否半选

const handleCheckAllChange = (val) => {
  visibleFields.value = val ? fieldSettings.map(field => field.prop) : []
  isIndeterminate.value = false
}

const handleCheckedChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === fieldSettings.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < fieldSettings.length
}

// 自定义 v-focus 指令
const vFocus = {
  mounted: el => {
    const input = el.querySelector('input') || el.querySelector('textarea')
    if (input) {
      input.focus()
    }
  }
}

const editingField = ref('')
const originalValue = ref(null)
const startEdit = field => {
  editingField.value = field
  // 保存原始值
  if (field.includes('.')) {
    // 处理嵌套属性
    const [parent, child] = field.split('.')
    originalValue.value = formData.value[parent]?.[child]
  } else {
    originalValue.value = formData.value[field]
  }
  if (field === 'logo') {
    showImgUpload.value = true
  }
}

const finishEdit = async field => {
  let currentValue
  if (field.includes('.')) {
    // 处理嵌套属性
    const [parent, child] = field.split('.')
    currentValue = formData.value[parent]?.[child]
  } else {
    currentValue = formData.value[field]
  }

  // 检查值是否发生变化
  if (currentValue !== originalValue.value) {
    const res = await updateSite(formData.value)
    if (res.code === 20000) {
      ElMessage.success('更新成功')
      emits('update')
    }
  }
  
  editingField.value = ''
  originalValue.value = null
}

const handleThemeColorChange = async () => {
  const res = await updateSite(formData.value)
  if (res.code === 20000) {
    ElMessage.success('更新成功')
    emits('update')
  }
}

// logo上传
const showImgUpload = ref(false)
const getImage = data => {
  formData.value.logo = data[0].url
}
watch(showImgUpload, val => {
  if (!val) {
    finishEdit('logo')
  }
})
</script>

<style lang="scss" scoped>
.base-info-box {
  .base-form {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;

    :deep(.el-form-item) {
      margin-bottom: 0;
      width: 100%;

      &.is-required .el-form-item__label:before {
        display: none;
      }
    }
  }

  .baidu-box{
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    .head{
      height: 40px;
      background: #DEE1E6;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px #fff solid;
      overflow: hidden;
      .title-box{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        background: #fff;
        padding: 10px;
        border-top-left-radius: 2px;
        border-top-right-radius: 2px;
        .ico-box{
          width: 16px;
          height: 16px;
          margin-right: 10px;
          img{
            width: 100%;
            height: 100%;
          }
        }
        .site-title{
          font-size: 14px;
          color: #797979;
          margin-right: 10px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .rigth-icon{
        i{
          margin-left: 5px;
          font-size: 16px;
        }
      }
    }
    .preview-content{
      min-height: 110px;
      background: #F1F3F4;
      padding: 17px 20px;
      box-sizing: border-box;
      .des1{
        font-size: 14px;
        color: #aaa;
      }
      .site-title{
        margin-top: 20px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        .name{
          font-size: 18px;
          color:#2440B3;
          text-decoration: underline;
        }
        .guanfang{
          width: 40px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 10px;
          background: #4E6EF2;
          color: #fff;
          border-radius: 4px;
          font-size: 14px;
        }
      }
      .site-body {
        display: flex;
        align-items: flex-start;
        margin-top: 10px;

        .site-logo {
          width: 60px;
          height: 60px;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #fff;
          border: 1px solid #eee;
          border-radius: 6px;
          margin-right: 16px;
          overflow: hidden;
          img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
          span {
            color: #aaa;
            font-size: 12px;
          }
        }

        .site-info-right {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          min-height: 60px;

          .site-des {
            font-size: 12px;
            color: #333;
            margin-bottom: 8px;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }
          .site-domain {
            font-size: 12px;
            color: #999;
            word-break: break-all;
          }
        }
      }
    }
  }

  .logo-setting,
  .editable-text {
    display: inline-flex;
    align-items: center;
    border-radius: 4px;
    cursor: pointer;
    overflow: hidden;

    .text-content {
      max-width: 90%;
      margin-right: 10px;
      font-size: 12px;
      @include textEllipsis(24px, 1);
    }

    &:hover {
      background-color: #f5f7fa;

      .edit-icon {
        opacity: 1;
      }
    }

    .edit-icon {
      font-size: 12px;
      opacity: 0;
      transition: opacity 0.2s;
      color: $mainColor;
    }

    .logo-img {
      width: 32px;
      height: 32px;
      object-fit: cover;
      border-radius: 4px;
    }
  }

  :deep(.el-textarea__inner) {
    font-family: inherit;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .setting-popover {
    .setting-title {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 12px;
    }

    :deep(.el-checkbox-group) {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    :deep(.el-divider--horizontal) {
      margin: 12px 0;
    }
  }
}
</style>
